//
//  ZZFBaseRequest.m
//  ZZFBaseServiceSDK
//
//  Created by quheng on 2017/8/21.
//  Copyright © 2017年 quheng. All rights reserved.
//

#import "BZBaseRequest.h"
#import "BZNetWorkCore.h"
#import <UIKit/UIKit.h>
#import <SVProgressHUD/SVProgressHUD.h>
#import "BZBaseInstance.h"
#import "NSError+NetworkError.h"
#import <Qiniu/QiniuSDK.h>
#import <Bugly/Bugly.h>



NSString  *const kBZHttpGetMethod   = @"GET";
NSString  *const kBZHttpPostMethod  = @"POST";
NSString  *const kBZHttpPatchMethod = @"PATCH";
NSString  *const kBZHttpPutMethod   = @"PUT";


@implementation BZBaseRequest


- (NSString *)requestHttpMethodWithType:(BZRequestType)requestType{

    
    NSString *httpMethod = nil;
    switch (requestType) {
        case BZGetRequest:
            httpMethod = kBZHttpGetMethod;
            break;
        case BZPostRequest:
            httpMethod = kBZHttpPostMethod;
            break;
        case BZPatchRequest:
            httpMethod = kBZHttpPostMethod;
            break;
        case BZPutRequest:
            httpMethod = kBZHttpPutMethod;
            break;
        default:
            break;
    }
    return httpMethod;

}


- (NSError *)handleRequestModel:(BZBaseRequestModel *)requestModel{

    NSError *error = nil;
    
    if (![requestModel.requestUri length]) {
        error = [NSError errorWithType:BZRequestURIError];
    }
    return error;
}


- (void)requestByModelAsync:(BZBaseRequestModel *)model
                    success:(void(^)(NSString *code,id response))success
                    failure:(void(^)(NSString *code,NSError *error))failure{

    NSError *error = [self handleRequestModel:model];
    if (error ) {
        if (failure) {
            failure(@"404",error);
        }
        return;
    }
    
    NSDictionary *headerParam = nil;
    
    
    if (model.hasSessionId) {
        
        NSString *sessionId = [BZBaseInstance shareInstance].sessionId;
        if ([sessionId length]) {
            headerParam = @{@"sessionId":sessionId};
        }else{
        
            if (failure) {
                
                error = [NSError errorWithType:BZRequestSessionIdError];
                failure(@"404",error);
            }
        }
    }

    
    [BZNetWorkCore requestByParam:model.param
                              uri:model.requestUri
                       httpMethod:[self requestHttpMethodWithType:model.requestType]
                      headerParam:headerParam
                          success:^(NSString *code, id responseObject) {
                              
                              //                                   responseObject = [ZZFDeleteNull changeType:responseObject];
                              success(code,responseObject);
                              
                          }failure:^(NSString *code, NSError *error) {
                              
                              
                              [Bugly reportError:error];

                              NSString *message  = [error.userInfo objectForKey:NSLocalizedDescriptionKey];
                              
                              [SVProgressHUD setMinimumDismissTimeInterval:0.75];
                              if (model.shouldToaster) {
                                  [SVProgressHUD showErrorWithStatus:message];
                                  
                              }
                              
//                                  if (model.shouldToaster) {
//                                      [MBProgressHUD showClueInView:[UIApplication  sharedApplication].keyWindow
//                                                              title:message
//                                                           duration:0.5];
//                                  }
                            
                          }];
    
    

}


- (BOOL)requestByModelSync:(BZBaseRequestModel *)model outError:(NSError *__autoreleasing *)outError{
    
    NSError *error = [self handleRequestModel:model];
    if (error ) {

        if (outError) {
            *outError = error;
        }
        return NO;
    }
    
    NSDictionary *headerParam = nil;
    
    
    if (model.hasSessionId) {
        
        NSString *sessionId = [BZBaseInstance shareInstance].sessionId;
        if ([sessionId length]) {
            headerParam = @{@"sessionId":sessionId};
        }else{
            
            if (outError) {
                
                *outError = [NSError errorWithType:BZRequestSessionIdError];
            }
            return NO;
        }
    }
    
    return [BZNetWorkCore requestByParamSync:model.param uri:model.requestUri
                                  httpMethod:[self requestHttpMethodWithType:model.requestType]
                                 headerParam:headerParam
                                    outError:outError];


}



- (void)uploadResourcesByDatas:(NSArray *) datas
                       success:(void(^)(NSArray* mediaPaths))success
                       failure:(void(^)(BOOL success, NSError *error))failure{
    
    
    NSDictionary *headerParam = nil;
    NSError *error            = nil;
        NSString *sessionId = [BZBaseInstance shareInstance].sessionId;
        if ([sessionId length]) {
            headerParam = @{@"sessionId":sessionId};
        }else{
            
            if (failure) {
                
                error = [NSError errorWithType:BZRequestSessionIdError];
                failure(NO,error);
            }
            return ;
        }
    
    __block long long customerId         = [BZBaseInstance shareInstance].userId;
    
    
    [BZNetWorkCore requestByParam:nil
                              uri:@""
                       httpMethod:kBZHttpPostMethod
                      headerParam:headerParam
                          success:^(NSString *code, id responseObject) {
        
                              dispatch_async(dispatch_get_global_queue(0,0), ^{
                                  
                                  NSString *qiNiuToken = [responseObject objectForKey:@"uptoken"];
                                  
                                  QNConfiguration *qnConfiguration = [QNConfiguration build:^(QNConfigurationBuilder *builder) {
//                                      builder.zone = [QNZone zone2];
                                  }];
                                  
                                  QNUploadOption *opt = [[QNUploadOption alloc] initWithMime:@"multipart/form-data"
                                                                             progressHandler:nil
                                                                                      params:@{@"scope":@"1",@"insertOnly":@"0"}
                                                                                    checkCrc:YES
                                                                          cancellationSignal:nil];
                                  
                                  __block QNUploadManager *upManager = [QNUploadManager sharedInstanceWithConfiguration:qnConfiguration];
                                  NSMutableArray* arr = [NSMutableArray array];
                                  NSUInteger count = datas.count;
                                  
                                  for (NSUInteger i = 0; i < count; i++) {
                                      
                                      NSData *data = datas[i];
                                      NSTimeInterval time= [[NSDate new] timeIntervalSince1970];
                                      NSString *filename = [NSString stringWithFormat:@"%@%lld%.f.%@",@"file",customerId,time,@"mp3"];
                                      
                                      dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
                                      
                                      [upManager putData:data
                                                     key:filename
                                                   token:qiNiuToken
                                                complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                                                    
                                                    
                                                    NSTimeInterval time= [[NSDate new] timeIntervalSince1970];
                                                    
                                                    
                                                    
                                                    if (!info.error) {
                                                        
                                                        NSString *portrait = [NSString stringWithFormat:@"http://%@/%@?time=%.0f",qiniuDomain,key,time];
                                                        //                                                                      [self.imagestrArr addObject:portrait];
                                                        [arr addObject:portrait];
                                                    }else{
                                                        
                                                        NSString * errorStr = [info.error.userInfo objectForKey:@"error"];
                                                        
                                                        if (![errorStr containsString:@"file exist"]) {
                                                            //
                                                            //                                                                          [self.failImages addObject:data];
                                                        }else{
                                                            
                                                            NSString *portrait = [NSString stringWithFormat:@"http://%@/%@?time=%.0f",qiniuDomain,key,time];
                                                            //                                                                          [self.imagestrArr addObject:portrait];
                                                            [arr addObject:portrait];
                                                            
                                                        }
                                                        
                                                    }
                                                    
                                                    dispatch_semaphore_signal(semaphore);
                                                    
                                                } option:opt];
                                      
                                      dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
                                  }
                                  
                                  if (arr.count == datas.count) {
                                      
                                      dispatch_sync(dispatch_get_main_queue(), ^{
                                          if (success) {
                                              success(arr);
                                          }
                                      });
                                  }
                                  
                              });
            
    } failure:^(NSString *code, NSError *error) {
        
        
        [Bugly reportError:error];
        
        if (failure) {
            failure(NO,error);
        }
    }];
    
}



@end
